﻿namespace WMS6.Web
{
    using System;
    using System.IO;
    using System.Web;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Xml;
    using WMS6.Web.CommonMethodServiceRef;
    using WMS6.Web.LoginServiceRef;

    public class Login : BasePage
    {
        protected Button btnLogin;
        protected HtmlForm form1;
        public int i;
        protected HtmlImage imgLogin;
        protected Image imgValidateCode;
        protected Label lblMsg;
        protected Label lblPassword;
        protected Label lblUserName;
        protected Label lblValidateCode;
        protected HtmlTableRow trValidateCode;
        protected HtmlInputPassword txtPassword;
        protected TextBox txtUserName;
        protected TextBox txtValidateCode;

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(this.txtUserName.Text.Trim()))
                {
                    this.lblMsg.Text = "请输入用户名!";
                }
                else if (string.IsNullOrEmpty(this.txtPassword.Value.Trim()))
                {
                    this.lblMsg.Text = "请输入密码!";
                }
                else
                {
                    if (this.trValidateCode.Visible)
                    {
                        if (string.IsNullOrEmpty(this.txtValidateCode.Text.Trim()))
                        {
                            this.lblMsg.Text = "请输入验证码!";
                            return;
                        }
                        if ((this.Session["ValidateCode"] != null) && (this.Session["ValidateCode"].ToString().ToUpper() != this.txtValidateCode.Text.Trim().ToUpper()))
                        {
                            this.lblMsg.Text = "验证码输入错误！";
                            return;
                        }
                    }
                    string userName = this.txtUserName.Text.Trim();
                    string userPwd = this.txtPassword.Value.Trim();
                    UserMstInfo userInfo = LoginServiceClientProxy.GetInstance().GetUserInfoByID(userName);
                    if (userInfo != null)
                    {
                        if (userInfo.Passwd == userPwd)
                        {
                            if (userInfo.IsActive == "Y")
                            {
                                userInfo.Preference = this.PreferenceSession(userInfo.UserID);
                                base.UserInfo = userInfo;
                                this.WriteLoginLog(userInfo.UserID, userInfo.UserName, "OK");
                                this.Session.Remove("ValidateCode");
                                //base.Server.Transfer("Frame_Main.aspx?from=Login", false);
                                base.Response.Redirect("default.aspx");
                            }
                            else
                            {
                                this.lblMsg.Text = "该用户已经被停用无法登陆!";
                            }
                        }
                        else
                        {
                            this.WriteLoginLog(userName, userName, "Failed");
                            if (this.ViewState["loginTimes"] != null)
                            {
                                this.i = int.Parse(this.ViewState["loginTimes"].ToString());
                                this.ViewState["loginTimes"] = this.i + 1;
                            }
                            else
                            {
                                this.ViewState["loginTimes"] = 1;
                            }
                            this.lblMsg.Text = "用户名或密码不正确!";
                        }
                    }
                    else
                    {
                        this.WriteLoginLog(userName, userName, "Failed");
                        if (this.ViewState["loginTimes"] != null)
                        {
                            this.i = int.Parse(this.ViewState["loginTimes"].ToString());
                            this.ViewState["loginTimes"] = this.i + 1;
                        }
                        else
                        {
                            this.ViewState["loginTimes"] = 1;
                        }
                        this.lblMsg.Text = "用户名或密码不正确!";
                    }
                }
            }
            catch (Exception ex)
            {
                SysLog.GetInstance().LogError(ex, "用户登录异常!");
            }
        }

        protected string CheckRegXML()
        {
            string reg = string.Empty;
            string MaxUsers = string.Empty;
            string Warehouses = string.Empty;
            string Expired = string.Empty;
            string LastLoginDate = string.Empty;
            string ActivationCode = string.Empty;
            string SystemKey = LicenseUtils.GenerateSystemKey();
            try
            {
                AppRegInfo appRegInfo = CommoneMethodServiceClientProxy.GetInstance().GetAppRegInfo();
                reg = this.GetLicenseContext(ref MaxUsers, ref Warehouses, ref Expired, ref LastLoginDate, ref ActivationCode);
                EnDeCrypt endeCrypt = new EnDeCrypt();
                if (!string.Equals(EnDeCrypt.EncryptString(endeCrypt.EnCrypt(SystemKey) + endeCrypt.EnCrypt(MaxUsers) + endeCrypt.EnCrypt(Warehouses) + endeCrypt.EnCrypt(Expired)), ActivationCode))
                {
                    return "授权文件无效!";
                }
                if (appRegInfo.UserCount > int.Parse(MaxUsers))
                {
                    reg = "系统用户超出注册数!";
                }
                else if (appRegInfo.WarehouseCount > int.Parse(Warehouses))
                {
                    reg = "仓库超出注册数!";
                }
                else if (DateTime.Now > DateTime.Parse(Expired))
                {
                    reg = "系统授权已过期!";
                }
                if (!string.IsNullOrEmpty(LastLoginDate))
                {
                    DateTime lastDate = DateTime.Today;
                    if (DateTime.TryParse(LastLoginDate, out lastDate))
                    {
                        if (DateTime.Today < lastDate)
                        {
                            return "系统日期时间已被修改!";
                        }
                        if (DateTime.Today > lastDate)
                        {
                            this.UpdateLastLoginDate(DateTime.Today);
                        }
                    }
                    return reg;
                }
                this.UpdateLastLoginDate(DateTime.Today);
            }
            catch (Exception ex)
            {
                reg = "Error:" + ex.Message;
            }
            return reg;
        }

        public string GetLicenseContext(ref string maxUser, ref string warehouses, ref string expired, ref string lastlogindate, ref string activationCode)
        {
            string reg = string.Empty;
            XmlDocument doc = new XmlDocument();
            XmlNodeReader reader = null;
            string s = string.Empty;
            try
            {
                string xmlPath = base.Server.MapPath("") + @"\License\license.qt";
                string xmlString = string.Empty;
                using (StreamReader sr = new StreamReader(xmlPath))
                {
                    xmlString = EnDeCrypt.DecryptString(sr.ReadToEnd());
                }
                doc.LoadXml(xmlString);
                reader = new XmlNodeReader(doc);
                while (reader.Read())
                {
                    switch (reader.NodeType)
                    {
                        case XmlNodeType.Element:
                            s = reader.Name;
                            goto Label_0166;

                        case XmlNodeType.Text:
                            if (string.Compare(s, "MaxUsers", true) != 0)
                            {
                                break;
                            }
                            maxUser = reader.Value;
                            goto Label_0166;

                        default:
                            goto Label_0166;
                    }
                    if (string.Compare(s, "Warehouses", true) == 0)
                    {
                        warehouses = reader.Value;
                    }
                    else if (string.Compare(s, "Expired", true) == 0)
                    {
                        expired = reader.Value;
                    }
                    else if (string.Compare(s, "LastLoginDate", true) == 0)
                    {
                        lastlogindate = reader.Value;
                    }
                    else if (string.Compare(s, "ActivationCode", true) == 0)
                    {
                        activationCode = reader.Value;
                    }
                Label_0166:;
                }
            }
            catch (Exception ex)
            {
                reg = ex.Message;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
            return reg;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.Page.Title = base.GetValueFromAppSettings("PAGE_LOGIN_TITLE");
            this.lblUserName.Text = base.GetValueFromAppSettings("LOGIN_USER_NAME");
            this.lblPassword.Text = base.GetValueFromAppSettings("LOGIN_PASSWORD");
            this.btnLogin.Text = base.GetValueFromAppSettings("LOGIN_BUTTON");
            string strimgUrl = base.GetValueFromAppSettings("LOGIN_IMAGE_URL");
            if (!File.Exists(base.Server.MapPath(strimgUrl)))
            {
                strimgUrl = "~/Images/login_logo.gif";
            }
            this.imgLogin.Src = strimgUrl;

            //

            if (!(string.IsNullOrEmpty(base.Request.QueryString["from"]) || !(base.Request.QueryString["from"].ToString() == "Logout")))
            {
                HttpContext.Current.Response.Write("<script language=javascript>top.location.href='Login.aspx'</script>");
                HttpContext.Current.Response.Write("<script language=javascript>window.location.href='Login.aspx'</script>");
                HttpContext.Current.Response.Write("<script language=javascript>window.parent.close()</script>");
            }
            if (this.ViewState["loginTimes"] != null)
            {
                this.i = int.Parse(this.ViewState["loginTimes"].ToString());
                if (this.i > 5)
                {
                    this.trValidateCode.Visible = true;
                }
            }
        }

        private PreferenceInfo PreferenceSession(string UserID)
        {
            PreferenceInfo Preference = new PreferenceInfo();
            PreferenceProfileInfo preferencePrifileInfo = LoginServiceClientProxy.GetInstance().GetPreferenceProfileByUserID(UserID);
            for (int i = 0; preferencePrifileInfo.PreferenceProfileDetailInfos.Count > i; i++)
            {
                switch (preferencePrifileInfo.PreferenceProfileDetailInfos[i].PreferenceID.ToUpper())
                {
                    case "COUNTRY":
                        Preference.Country = preferencePrifileInfo.PreferenceProfileDetailInfos[i].PreferenceValue;
                        break;

                    case "CURRENCY":
                        Preference.Currency = preferencePrifileInfo.PreferenceProfileDetailInfos[i].PreferenceValue;
                        break;

                    case "DATE_FORMAT":
                        Preference.DateFormat = preferencePrifileInfo.PreferenceProfileDetailInfos[i].PreferenceValue;
                        break;

                    case "DIGITS_NO":
                        Preference.Digits_No = preferencePrifileInfo.PreferenceProfileDetailInfos[i].PreferenceValue;
                        break;

                    case "LANG":
                        Preference.Lang = preferencePrifileInfo.PreferenceProfileDetailInfos[i].PreferenceValue;
                        break;

                    case "TIME_FORMAT":
                        Preference.Time_Format = preferencePrifileInfo.PreferenceProfileDetailInfos[i].PreferenceValue;
                        break;

                    case "TIMEZONE":
                        Preference.TimeZone = preferencePrifileInfo.PreferenceProfileDetailInfos[i].PreferenceValue;
                        break;

                    case "THEMES":
                        Preference.Themes = preferencePrifileInfo.PreferenceProfileDetailInfos[i].PreferenceValue;
                        break;

                    case "TIME":
                        Preference.Time = preferencePrifileInfo.PreferenceProfileDetailInfos[i].PreferenceValue;
                        break;
                }
            }
            return Preference;
        }

        protected string UpdateLastLoginDate(DateTime date)
        {
            string result = string.Empty;
            try
            {
                XmlDocument doc = new XmlDocument();
                bool AddLastDate = true;
                string xmlPath = base.Server.MapPath("") + @"\License\license.qt";
                string xmlString = string.Empty;
                using (StreamReader sr = new StreamReader(xmlPath))
                {
                    xmlString = EnDeCrypt.DecryptString(sr.ReadToEnd());
                }
                doc.LoadXml(xmlString);
                XmlNodeList nodeList = doc.SelectSingleNode("License").ChildNodes;
                foreach (System.Xml.XmlNode node in nodeList)
                {
                    if (string.Compare(node.Name, "LastLoginDate", true) == 0)
                    {
                        node.InnerText = date.ToString("yyyy-MM-dd");
                        AddLastDate = false;
                        break;
                    }
                }
                if (AddLastDate)
                {
                    XmlElement xmlelem = doc.CreateElement("LastLoginDate");
                    xmlelem.AppendChild(doc.CreateTextNode(date.ToString("yyyy-MM-dd")));
                    doc.ChildNodes.Item(1).AppendChild(xmlelem);
                }
                using (StreamWriter sw = new StreamWriter(xmlPath))
                {
                    sw.Write(EnDeCrypt.EncryptString(doc.OuterXml));
                }
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }
            return result;
        }

        private void WriteLoginLog(string userID, string userName, string loginStatus)
        {
            SysLoginLogInfo sysLoginLogInfo = new SysLoginLogInfo {
                LoginUserID = userID,
                LoginUserName = userName,
                LoginStatus = loginStatus,
                LoginMode = "MainSystem",
                LoginTime = DateTime.Now,
                LoginIpAddress = base.Request.UserHostAddress,
                LoginMachineName = base.Request.UserHostName,
                LoginMacAddress = "",
                CreatedBy = userID
            };
            LoginServiceClientProxy.GetInstance().WriteLoginLog(sysLoginLogInfo);
        }
    }
}

